package com.pet.backend.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pet.backend.pojo.*;
import com.pet.backend.service.impl.GoodsServiceImpl;
import com.pet.backend.service.impl.OrdersServiceImpl;
import com.pet.backend.service.impl.UserServiceImpl;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  订单
 * </p>
 *
 * @author pet
 * @since 2024-07-13
 */
@CrossOrigin
@RestController
@RequestMapping("/orders")
public class OrdersController {

    @Resource
    private OrdersServiceImpl ordersService;

    @Resource
    private GoodsServiceImpl goodsService;

    @Resource
    private UserServiceImpl userService;

    // 搜索
    @GetMapping("/search/{name}/{current}")
    public Vo<Orders> search(@PathVariable("name") String name, @PathVariable("current") Integer current){
        if (name.equals("")){
            return new Vo<>();
        }
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(Orders::getName,name);
        Page<Orders> ordersPage = new Page<>(current <= 0 ? 1 : current,10);
        IPage<Orders> page = ordersService.page(ordersPage, wrapper);
        if (page.getTotal() == 0){
            // 表示没有数据
            return new Vo<>();
        }
        List<Orders> orders = page.getRecords();
        // 总条数
        long total = page.getTotal();
        // 当前页
        long pageCurrent = page.getCurrent();
        // 返回
        return new Vo<>(true,orders,pageCurrent,total);
    }
    // 分页查询
    @GetMapping("/page/{current}")
    public Vo<Orders> page(@PathVariable("current") Integer current) {
        Page<Orders> ordersPage = new Page<>(current >= 0 ? current : 1, 10);
        IPage<Orders> page = ordersService.page(ordersPage);
        if (page.getTotal() == 0) {
            // 表示没有数据直接返回
            return new Vo<>(false, "目前没有订单！");
        }
        // 数据
        List<Orders> orders = page.getRecords();
        // 当前页
        long curr = page.getCurrent();
        // 总记录数
        long total = page.getTotal();
        // 返回
        return new Vo<>(true, orders, curr, total);
    }
    // 删除
    @GetMapping("/delete/{id}")
    public Vo<Message> delete(@PathVariable("id") String id){
        boolean b = ordersService.removeById(id);
        if (b){
            return new Vo<>(b,"删除成功！");
        }else {
            return new Vo<>(b,"删除失败，请稍后重试！");
        }
    }

    // 新增
    @PostMapping("/insert")
    public Vo<Orders> insert(@RequestBody Orders orders){
        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Goods::getId,orders.getSId());
        // 获取到商品
        Goods one = goodsService.getOne(queryWrapper);
        // 进行库存扣减
        if (one.getInventory() > 0 && one.getInventory() >= orders.getCount()){
            // 这里表示库存是够的，在判断余额
            LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(User::getId,orders.getUId());
            User user = userService.getOne(lambdaQueryWrapper);
            // 判断余额是否够
            int i = user.getBalance().compareTo(orders.getTotalprice());
            if (i > 0){
                // 表示余额足够，扣减余额
                UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
                // 设置条件
                updateWrapper.eq("id",user.getId());
                updateWrapper.set("balance",user.getBalance().subtract(orders.getTotalprice()));
                // 调用数据库
                userService.update(updateWrapper);
                // 这里表示成立可以进行新增订单
                UpdateWrapper<Goods> wrapper = new UpdateWrapper<>();
                wrapper.eq("id",orders.getSId());
                wrapper.set("inventory",one.getInventory() - orders.getCount());
                boolean b = goodsService.update(wrapper);
                if (b){
                    boolean flag = ordersService.save(orders);
                    return new Vo<>(flag,"下单成功！");
                }else {
                    return new Vo<>(b,"下单失败，请稍后重试");
                }
            }else {
                return new Vo<>(false,"你的余额不够,请进行充值");
            }
        }else {
            return new Vo<>(false,"库存不够！");
        }
    }
    // 根据用户id进行查询订单
    @GetMapping("/select/{uid}")
    public Vo<Orders> select(@PathVariable("uid") Long uId){
        // 定义条件查询器
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        // 添加条件
        wrapper.eq(Orders::getUId,uId);
        List<Orders> list = ordersService.list(wrapper);
        if (list.size() == 0){
            return new Vo<>(false,"目前你还没有订单");
        }
        return new Vo<>(true,list);
    }

}
